import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
import Request from '@/js/API/index.js';
import router from '@/router';
import Common from '@/js/common.js';

const store = new Vuex.Store({
  state: {},
  getters: {
    permissionMenu(state) {
      return state.permissionMenu
    }
  },
  mutations: {
    SAVE_PERMISSION: (state, data) => {
      state.getPermission = true;
      state.permissionMenu = data;
    },
    SAVE_DATA: (state, { key, data }) => {
      state[key] = data;
    },
  },
  actions: {
    savePermission({ commit }, data) {
      return new Promise(resolve => {
        const accountDataInfo = Common.getCookie('accountDataInfo') && JSON.parse(Common.getCookie('accountDataInfo'))
        Request.getMenuByToken({
          params: {
            projectId: sessionStorage.projectId || accountDataInfo.projectId,
            Authorization: sessionStorage.token || accountDataInfo.token
          },
          success: (data) => {
            let dynamicRoutes = [];
            data.forEach(o => {
              dynamicRoutes.push(o.menuUrl);
            });
            commit("SAVE_PERMISSION", dynamicRoutes);
            const initRoutes = router.options.routes;
            const routes = [];
            // for (let i in asyncRoutesMap) {
            //   if (dynamicRoutes.includes(i)) {
            //     const parent = asyncRoutesMap[i].parent;
            //     if (parent) {
            //       let router = {};
            //       for (let i = 0; i < parent.length; i++) {
            //         let children = []
            //         if (i === 0) {
            //           children = initRoutes;
            //         }
            //         router = children.find(o => {
            //           return o.name === parent[i]
            //         })
            //         if (router) children = router.children || [];
            //       }
            //       if (router) {
            //         router.children.push({
            //           path: asyncRoutesMap[i].path,
            //           name: asyncRoutesMap[i].name,
            //           component: asyncRoutesMap[i].component
            //         })
            //         routes.push(router);
            //       }
            //     } else routes.push(asyncRoutesMap[i]);
            //   }
            // }
            resolve(routes);
          }
        })
      })
    },
    saveData({ commit }, { key, data }) {
      commit('SAVE_DATA', { key, data });
    },
  }
});

export default store;
